package com.wuyou.simple;

/**
 * 999. 可以被一步捕获的棋子数
 *
 * @Date 2024/12/6 10:33
 * @Author 无忧
 */
public class NumRookCaptures {

    public static void main(String[] args) {
        char[][] board = {{'.', '.', '.', '.', '.', '.', '.', '.'}, {'.', '.', '.', 'p', '.', '.', '.', '.'}, {'.', '.', '.', 'R', '.', '.', '.', 'p'}, {'.', '.', '.', '.', '.', '.', '.', '.'}, {'.', '.', '.', '.', '.', '.', '.', '.'}, {'.', '.', '.', 'p', '.', '.', '.', '.'}, {'.', '.', '.', '.', '.', '.', '.', '.'}, {'.', '.', '.', '.', '.', '.', '.', '.'}};
        NumRookCaptures numRookCaptures = new NumRookCaptures();

        System.out.println(numRookCaptures.numRookCaptures(board));
    }

    public int numRookCaptures(char[][] board) {
        int x = 0, y = 0, length = board.length;
        for (int i = 0; i < length; i++) {
            for (int j = 0; j < length; j++) {
                if (board[i][j] == 'R') {
                    x = i;
                    y = j;
                    break;
                }
            }
            if (x != 0 || y != 0) {
                break;
            }
        }
        return countByXUp(board, x, y) + countByXDown(board, x, y) + countByYLeft(board, x, y) + countByYRight(board, x, y);
    }

    private int countByXUp(char[][] board, int x, int y) {
        // 上边
        int tempX1 = x - 1, count = 0;
        while (tempX1 >= 0) {
            if (board[tempX1][y] == 'B') {
                break;
            }
            if (board[tempX1--][y] == 'p') {
                count++;
                break;
            }
        }
        return count;
    }

    private int countByXDown(char[][] board, int x, int y) {
        // 下边
        int tempX = x + 1, count = 0;
        while (tempX < board.length) {
            if (board[tempX][y] == 'B') {
                break;
            }
            if (board[tempX++][y] == 'p') {
                count++;
                break;
            }
        }
        return count;
    }

    private int countByYLeft(char[][] board, int x, int y) {
        // 左边
        int tempY = y - 1, count = 0;
        while (tempY >= 0) {
            if (board[x][tempY] == 'B') {
                break;
            }
            if (board[x][tempY--] == 'p') {
                count++;
                break;
            }
        }
        return count;
    }

    private int countByYRight(char[][] board, int x, int y) {
        // 右边
        int tempY = y + 1, count = 0;
        while (tempY < board.length) {
            if (board[x][tempY] == 'B') {
                break;
            }
            if (board[x][tempY++] == 'p') {
                count++;
                break;
            }
        }
        return count;
    }
}
